package cc.iotkit.test;

import cc.iotkit.plugins.mattress.parser.CRC8;
import cc.iotkit.plugins.mattress.parser.SocketUtil;
import io.vertx.core.AbstractVerticle;
import io.vertx.core.Handler;
import io.vertx.core.buffer.Buffer;
import io.vertx.core.json.JsonObject;
import io.vertx.core.net.NetServer;
import io.vertx.core.parsetools.RecordParser;
import lombok.extern.slf4j.Slf4j;

import java.util.Objects;


@Slf4j
public class TcpServerVerticle extends AbstractVerticle {

    @Override
    public void start() throws Exception {
        int len_header = 4;
        NetServer server = vertx.createNetServer();
        server.connectHandler(socket ->{
            RecordParser parser = RecordParser.newFixed(len_header);
            parser.setOutput(new Handler<Buffer>() {
                int size = -1;
                byte crc = -1;
                Buffer headBuf = null;
                @Override
                public void handle(Buffer buffer) {
                    if(-1==size){
                        String str = SocketUtil.bytesToHexString(buffer.getBytes());
                        String headStr = str.substring(0, 4);
                        if (!"abcd".equals(headStr)) {
                            log.error("MSG ERROR: Not start with abcd");
                            return;
                        }
                        log.info("head信息获取："+str);
                        //取出长度
                        size = buffer.getByte(2);
                        crc = buffer.getByte(3);
                        headBuf = Buffer.buffer(buffer.getBytes());
                        //动态修改长度
                        parser.fixedSizeMode(size);
                        System.out.println("表头解析结束++++++++++++++++++++++++++++");
                    } else {
                        //如果size != -1, 说明已经接受到长度信息了，接下来的数据就是protobuf可识别的字节数组
                        byte[] buf = buffer.getBytes();
                        log.info("data信息获取："+ SocketUtil.bytesToHexString(buf));
                        //校验信息CRC
                        byte realCrc = CRC8.calcCrc8(buf);
                        if(realCrc != crc){
                            log.error("MSG ERROR:crc error");
                        }
                        if(Objects.nonNull(headBuf)){
                            byte[] mattressData = headBuf.appendBytes(buf).getBytes();
                            vertx.eventBus().send("mattress.forward",new JsonObject().put("mattress", mattressData));
                            log.info("head+data信息获取："+
                                    SocketUtil.bytesToHexString(mattressData));
                        }
                        //处理完后要将长度改回
                        parser.fixedSizeMode(4);
                        //重置size变量
                        size = -1;
                        crc = -1;
                        headBuf = null;
                        System.out.println("数据解析结束++++++++++++++++++++++++++++");
                    }
                }
            });
            socket.handler(parser);
        });
        server.listen(1234,"127.0.0.1", res->{
            if(res.succeeded()){
                System.out.println("tcp server is listening at 1234");
            }else {
                System.out.println(res.cause());
            }

        });
    }

}